import React from 'react'
import PropTypes from 'prop-types'

class Timer extends React.Component {

    constructor(props) {
        super(props);
        this.timmerId = undefined
        this.state = {
            date: new Date(),
            started: false
        }
    }

    render() {
        return(
            <div className="timer">
                <p>Hello&nbsp;{this.props.name}</p>
                <p>
                    <span>现在的时间是：</span>
                    <span>{this.state.date.toLocaleDateString()}</span>
                    <span>&nbsp;</span>
                    <span>{this.state.date.toLocaleTimeString()}</span>
                </p>
                <button onClick={this.state.started ? this.pause : this.start}>
                    {this.state.started ? "暂停" : "开始"}
                </button>
            </div>
        )
    }

    componentDidMount() {
        this.start()
    }

    componentWillUnmount() {
        this.pause()
    }

    tick() {
        this.setState({
            date: new Date()
        })
    }

    start = () => {
        this.timmerId = setInterval(
            () => this.tick(),
            1000
        )
        this.setState({
            started: true
        })
    }

    pause = () => {
        if (this.timmerId) {
            clearInterval(this.timmerId)
            this.setState({
                started: false
            })
        }
    }
}

Timer.propTypes = {
    name: PropTypes.string.isRequired
}

export default Timer
